angular.module('starter.controllers', [])

  .controller('HomeCtrl', function($scope,$state,UserFactory,ENV,$rootScope,$timeout) {
    $scope.findPersonInfo= function (id) {
      $state.go("tab.person_info",{personId:id});
    }
    $scope.picurl=ENV.pic;

    $scope.chooseRole= function (roleId,role) {
      ENV.role=role;
      $state.go("tab.sort",{sortId:roleId});
    }
    UserFactory.getTogetrankServer();
    console.log(ENV.userPhone+"------------");
    UserFactory.getAllRoleServer();

    $scope.$on('UserFactory.getTogetrankServer', function () {
        $scope.trankList=UserFactory.returnTrank();
      $.fn.raty.defaults.path = 'lib/dark/img';
        $timeout(function () {
          for (var i = 0; i < $scope.trankList.length; i++) {
            $('#home_' + i).raty({readOnly: true, score: $scope.trankList[i].grade});
          }
        },1000);
    });

    $scope.$on('UserFactory.getAllRoleServer', function () {
       var roleList=UserFactory.returnAllRole();
       $scope.roleArray=[];
       for(var i=0;i<3;i++){
          var online=[];
          for(var j=0;j<4;j++){
            online.push(roleList[j+i*4]);
          }
          $scope.roleArray.push(online);
       }
       console.log($scope.roleArray);
    });

    $scope.$on('$ionicView.beforeEnter', function() {
      $rootScope.hideTabs = '';
      console.log('beforeEnter');
    });

  })
  .controller('PersonInfoCtrl', function($scope,$stateParams,UserFactory,ENV,$state,$timeout) {
      UserFactory.getEmployeeInfoByIdServer($stateParams.personId);
      $(".info-tab div").click(function () {
        $(this).addClass('tab-emp').siblings().removeClass();
        $('.content').hide().eq($(".info-tab div").index(this)).show();
      });
      $scope.$on('getEmployeeInfoByIdServer', function () {
          $scope.employeeInfo=UserFactory.returnEmployeeInfo();
          $scope.employeeInfo.headImgUrl=ENV.api+$scope.employeeInfo.headImgUrl;
        console.log($scope.employeeInfo.headImgUrl);
          UserFactory.getRoleInfoServer($scope.employeeInfo.curRoleId);
      });
      $scope.$on('getRoleInfoServer', function () {
          $scope.roleInfo=UserFactory.returnRoleInfo();
          ENV.role=$scope.roleInfo.identity;
      });

      UserFactory.getEmployeeComment($stateParams.personId);
      $scope.$on('getEmployeeComment', function () {
        $scope.employeeComment=UserFactory.returnEmployeeComment();
        console.log($scope.employeeComment);
        $timeout(function () {
          for(var i=0;i<$scope.employeeComment.length;i++){
            $('#person_info_'+i).raty({ readOnly: true, score: $scope.employeeComment[i].rank });
          }
        },1000);

      });

       $.fn.raty.defaults.path = 'lib/dark/img';
       $('#person_info_star').raty({ readOnly: true, score: 3 });



      $scope.addOrder= function () {
        ENV.roleName=$scope.employeeInfo.name;
        ENV.price=$scope.employeeInfo.wage;
        $state.go("tab.add_order",{employeeId:$scope.employeeInfo.id,roleId:$scope.employeeInfo.curRoleId})
      }


  })
  .controller('SortCtrl', function($scope,$stateParams,UserFactory,$state,$timeout) {
    $scope.sortType=$stateParams.sortId;
    UserFactory.getEmployeeByRoleIdServer($stateParams.sortId);

    $scope.$on('getEmployeeByRoleIdServer', function () {
      $scope.sortInfo=UserFactory.returnEmployeeListByRoleId();
      $.fn.raty.defaults.path = 'lib/dark/img';
      $timeout(function () {
        for (var i = 0; i < $scope.sortInfo.page.result.length; i++) {
          $('#sort_' + i).raty({readOnly: true, score: $scope.sortInfo.page.result[i].grade});
          console.log($scope.sortInfo.page.result[i].grade);
        }
      },1000);
    });

    $scope.findPersonInfo= function (id) {
      $state.go("tab.person_info",{personId:id});
    }

  })
  .controller('LoginCtrl', function($scope,UserFactory,DpDataBase,$state,ENV) {
    $scope.logindisbled=false;
    $scope.user={
      phone:"",
      password:''
    }
    $scope.submitForm = function(isValid) {
      $scope.submitted = true;
      /*注册表单验证*/
      if (isValid) {
        $scope.logindisbled=true;
        UserFactory.login($scope.user);
      }
    }
    $scope.$on('UserFactory.login', function () {
      $scope.logindisbled=false;
    });
  })

  .controller('OrderCtrl', function($scope,UserFactory,ENV) {

    //$scope.showloading=true;
    ////初始化
    //$scope.type="unReach";
    ////UserFactory.getUnReachOrderList(null);
    //$scope.unReachOrderState="brb-line reture-tab-on";
    //$scope.reachOrderState="";
    //$scope.allOrderState="";
    //$scope.$on('OrderList.OrdersUpdated', function () {
    //  $scope.showloading=false;
    //  //$scope.orderList=UserFactory.returnOrderList();
    //  console.log("----------");
    //  console.log($scope.orderList);
    //});

    //$scope.chooseOrderType= function (type) {
    //   $scope.type=type;
    //   $scope.showloading=true;
    //   //getInitData();
    //};
    //function getInitData(key){
    //  if($scope.type=="unReach"){
    //    $scope.unReachOrderState="brb-line reture-tab-on";
    //    $scope.reachOrderState="";
    //    $scope.allOrderState="";
    //    UserFactory.getUnReachOrderList(key);
    //  }else if($scope.type=="reach"){
    //    $scope.unReachOrderState="";
    //    $scope.reachOrderState="brb-line reture-tab-on";
    //    $scope.allOrderState="";
    //    UserFactory.getReachOrderList(key);
    //  }else{
    //    UserFactory.getOrderList(key);
    //    $scope.unReachOrderState="";
    //    $scope.reachOrderState="";
    //    $scope.allOrderState="brb-line reture-tab-on";
    //  }
    //}
    //$scope.doRefresh= function () {
    //  $scope.showloading=true;
    //  getInitData();
    //  $scope.$broadcast('scroll.refreshComplete');
    //};
    //$scope.loadMore = function() {
    //  if($scope.type=="unReach"){
    //    $scope.unReachOrderState="brb-line reture-tab-on";
    //    $scope.reachOrderState="";
    //    $scope.allOrderState="";
    //    UserFactory.getMoreUnReachOrderList(null);
    //  }else if($scope.type=="reach"){
    //    $scope.unReachOrderState="";
    //    $scope.reachOrderState="brb-line reture-tab-on";
    //    $scope.allOrderState="";
    //    UserFactory.getMoreReachOrderList(null);
    //  }else{
    //    UserFactory.getMoreOrderList(null);
    //    $scope.unReachOrderState="";
    //    $scope.reachOrderState="";
    //    $scope.allOrderState="brb-line reture-tab-on";
    //  }
    //  $scope.$broadcast('scroll.infiniteScrollComplete');
    //};

    //$scope.moreDataCanBeLoaded = function() {
    //  return UserFactory.hasNextPage();
    //};
    //$scope.textChange= function (val) {
    //  getInitData(val);
    //  //HomeFactory.getSearchKey(getLocalArea.city_id,ENV.homeSearch,val,userToken);
    //}

    if(ENV.userId==""){
      layer.msg("请先登入");
    }else{
      if(ENV.userRole=="employer"){
        $scope.role="1";
        UserFactory.getOrderList();
      }else{
        $scope.role="2";
        UserFactory.getOrderList2();
      }

    }

    $scope.$on('getOrderList', function () {
      console.log($scope.role);
        $scope.$apply(function () {
          $scope.orderList = UserFactory.returnOrder();
        });
      console.log($scope.orderList);
    });
    $scope.$on('getOrderList2', function () {
      console.log($scope.role);
      $scope.$apply(function () {
        $scope.orderList2=UserFactory.returnOrder2();
      });

      console.log($scope.orderList2);
    });

  })
  .controller('OrderDetailCtrl',function($scope,UserFactory,$stateParams,$ionicPopup,ENV){
    $scope.showloading=true;
    UserFactory.getOrderDetail($stateParams.orderId);
    $scope.$on('UserFactory.getOrderDetail', function () {
         //$scope.showloading=false;
        $scope.orderDetailInfo=UserFactory.returnOrderDetai();
    });
    if(ENV.userRole=="employer"){
      $scope.role=1;
    }else{
      $scope.role=2;
    }

    $scope.changeOrderState= function (id,type,status) {
      UserFactory.changeOrderState(id,type,status);
    };

/*    $scope.sureReach= function (orderId) {
      var confirmPopup = $ionicPopup.confirm({
        title: '提示',
        okText:'确定',
        template: '您确认送达了吗！',
        cancelText:'取消',
        cssClass: 'dp-alert'
      });
      confirmPopup.then(function(res) {
        if(res) {
          UserFactory.signOrder(orderId);
        } else {
          return;
        }
      });

    };

    $scope.refuseSign= function (orderId) {
      $scope.data={
        wifi:'',
      }
      var myPopup = $ionicPopup.show({
        template: '<textarea type="text" class="refuse-input" placeholder="{{reasonError}}" ng-model="data.wifi"/>',
        title: '提示:填写拒绝理由',
        scope: $scope,
        cssClass: 'dp-alert',
        buttons: [
          { text: '取消' },
          {
            text: '<b>确定</b>',
            type: 'button-positive',
            onTap: function(e) {
              if (!$scope.data.wifi) {
                $scope.reasonError="理由不能为空";
                //不允许用户关闭，除非他键入wifi密码
                e.preventDefault();
              } else {
                return $scope.data.wifi;
              }
            }
          },
        ]
      });
      myPopup.then(function(res) {
        if(res){
          console.log('Tapped!', res);
          UserFactory.refuseSignOrder(orderId,res);
        }
      });

    };*/

  })

  .controller('SettingCtrl', function($scope,UserFactory,ENV,$ionicPopup,fileReader,$http) {

    if(ENV.userPhone!=''&&ENV.userId!=''){
      //获取用户信息
      console.log("获取用户信息");
      $scope.userInfo={
        name:ENV.userName,
        phone:ENV.userPhone,
        id:ENV.userId
      }
      if(ENV.userRole=='employer'){
        $scope.employerState="choose-role";

      }else{
        $scope.employerState="";
      }
      $scope.isLogin=true;//用户是否登入标志

    }else{
      //初始化
      $scope.isLogin=false;//用户是否登入标志
      $scope.employerState="choose-role";
      $scope.employeeState="";
      $scope.loginOp=""
      $scope.signOp="choose-op";

      //声明对象
      $scope.userData={
      };
    }

     //选中雇主
     $scope.chooseEmployer=function(){
       $scope.employerState="choose-role";
       $scope.employeeState="";
       $scope.userData={};
     }
     //选中雇员
     $scope.chooseEmployee=function(){
       $scope.employerState="";
       $scope.employeeState="choose-role";
       $scope.userData={};
     }
     //选中雇主登入
     $scope.employerLogin= function () {
       $scope.loginOp="";
       $scope.signOp="choose-op";
       $scope.userData={};
     }
     //选中雇主注册
     $scope.employerSign= function () {
       $scope.loginOp="choose-op";
       $scope.signOp="";
       $scope.userData={};
     }

     $scope.submitLoginForm= function (type) {
        console.log($scope.userData);
        if(type=="employer"){
          UserFactory.employerLoginServer($scope.userData);
        }else{
          UserFactory.employeeLoginServer($scope.userData);
        }
     };

     $scope.submitSignUpForm= function (type) {
        //console.log($scope.userData);
        if(type=="employer"){
          if($scope.userData.seeappl==undefined||$scope.userData.seeappl==false){
            layer.msg("请先勾选申请须知");
          }else{
            UserFactory.employerSignUpServer($scope.userData);
          }
        }else{
          var imgPath = $("#touxiang").val();
          if (imgPath == "") {
            alert("请选择上传图片！");
            return;
          }
          //判断上传文件的后缀名
          var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
          if (strExtension != 'jpg' && strExtension != 'gif'
            && strExtension != 'png' && strExtension != 'bmp') {
            alert("请选择图片文件");
            return;
          }
          $.ajax({
            type: "POST",
            url: ENV.api+"doUpload",
            data: { imgPath: $("#touxiang").val() },
            cache: false,
            success: function(data) {
              console.log(data);
              alert("上传成功");
              $("#imgDiv").empty();
              $("#imgDiv").html(data);
              $("#imgDiv").show();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              alert("上传失败，请检查网络后重试");
            }
          });
          console.log($scope.userData);
        }
     };




    //$scope.onFileSelect = function($files) {
    //
    //  console.log($files);
    //  for (var i = 0; i < $files.length; i++) {
    //    var file = $files[i];
    //    $scope.upload = $upload.upload({
    //      url: 'server/upload/url',
    //      data: {myObj: $scope.myModelObj},
    //      file: file,
    //    }).progress(function (evt) {
    //      console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
    //    }).success(function (data, status, headers, config) {        // file is uploaded successfully
    //      console.log(data);
    //    });
    //  }
    //};
    //
    //$scope.getFile = function () {
    //  fileReader.readAsDataUrl($scope.file, $scope)
    //    .then(function(result) {
    //      $scope.imageSrc = result;
    //    });
    //};
    //
    //
    //var postData = {
    //  //vacationType: $scope.leave.type,
    //  //reason: $scope.leave.reason,
    //  //familyRelation: +$scope.leave.type == 7 ? $scope.leave.relation : "",
    //  //startTime: startTime,
    //  //endTime: endTime,
    //  fileName: $scope.imageSrc,
    //  //workDelivers: workDelivers,
    //  //ccmailNickNames: sendPersons,
    //  //realDays: +$scope.leave.type == 8 ? $scope.leave.timeLong : ""
    //};
    //var promise = postMultipart('/doUpload', postData);
    //function postMultipart(url, data) {
    //  var fd = new FormData();
    //  angular.forEach(data, function(val, key) {
    //    fd.append(key, val);
    //  });
    //  var args = {
    //    method: 'POST',
    //    url: url,
    //    data: fd,
    //    headers: {'Content-Type': undefined},
    //    transformRequest: angular.identity
    //  };
    //  return $http(args);
    //}

    /*获取验证码*/
     $scope.getCode= function () {
     }

    UserFactory.getAllRoleServer();
    $scope.$on('UserFactory.getAllRoleServer', function () {
      $scope.roleList = UserFactory.returnAllRole();
    });


  })
  .controller('OptionCtrl', function($scope,ENV,$ionicPopup,$state) {
    $scope.quitAccout= function () {
      // 一个确认对话框
      var confirmPopup = $ionicPopup.confirm({
        title: '提示',
        template: '你确定要退出该账号吗?',
        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
        cancelText: '取消',
        cssClass: 'dp-alert'
      });
      confirmPopup.then(function(res) {
        if(res) {
          console.log('You are sure');
          ENV.userPhone="";
          ENV.userId="";
          location.reload();
          $state.go('tab.setting');
        } else {
          console.log('You are not sure');
          return;
        }
      });
    };

  })
  .controller('EmployerInfoCtrl', function($scope,ENV,UserFactory,FileUploader) {
    $scope.employerInfo={
      headimgurl:'',
      username:'',
      phoneNo:'',
      sex:'',
      email:'',
      integral:'',
      grade:'',
      address:'',
      userId:ENV.userId,
    }
    UserFactory.getEmployerInfoServer(ENV.userId);

    $scope.$on('getEmployerInfoServer', function () {
      var employerInfo=UserFactory.returnEmployerInfo();
      $scope.employerInfo.headimgurl=ENV.api+employerInfo.headimgurl;
      console.log($scope.employerInfo.headimgurl);
      $scope.employerInfo.username=employerInfo.username;
      $scope.employerInfo.phoneNo=employerInfo.phoneNo;
      $scope.employerInfo.sex=employerInfo.sex;
      $scope.employerInfo.email=employerInfo.email;
      $scope.employerInfo.integral=employerInfo.integral;
      $scope.employerInfo.grade=employerInfo.grade;
      $scope.employerInfo.address=employerInfo.address;
    });

    $scope.submitEditEmployer= function () {
      console.log($scope.employerInfo);
      UserFactory.editEmployerInfoServer($scope.employerInfo);
    }

    var uploader = $scope.uploader = new FileUploader({
      url: ENV.api+'api/user/doUpload?userId='+ENV.userId,
    });

      uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
      };
      uploader.onAfterAddingFile = function(fileItem) {
        console.info('onAfterAddingFile', fileItem);
      };
      uploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
      };
      uploader.onBeforeUploadItem = function(item) {
        console.info('onBeforeUploadItem', item);
      };
      uploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
      };
      uploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
      };
      uploader.onSuccessItem = function(fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
      };
      uploader.onErrorItem = function(fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
      };
      uploader.onCancelItem = function(fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
      };
      uploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', response);
        $scope.$apply(function () {
          $scope.employerInfo.headimgurl=ENV.api+response.createPath;
        })
      };
      uploader.onCompleteAll = function() {
        console.info('onCompleteAll');
      };

      //console.info('uploader', uploader);
      //uploader.onSuccessItem = function (fileItem, response, status, headers) {
      //  console.info('onSuccessItem', fileItem, response, status, headers);
      //}



    //uploader.filters.push({
    //  name: 'customFilter',
    //  fn: function(item /*{File|FileLikeObject}*/, options) {
    //    return this.queue.length < 10;
    //  }
    //});

  })
  .controller('AddOrderCtrl', function($scope,ENV,$stateParams,UserFactory) {

    //alert(ENV.userId);
    $scope.orderInfo={
      userId:ENV.userId,
      employeeId:$stateParams.employeeId,
      roleId:$stateParams.roleId,
      serverdate:'',
      timeSelect:'',
      times:'',
      servertime:'',
      servertime2:'',
      address:'',
      orderType:2,
      payType:'',
      interviewType:'',
      isAgreeTerms:true,
      priceDec:ENV.price,
      enjoy:''
    }

    $scope.orderType1="hide";
    $scope.orderType2="hide";
    $scope.orderType3="hide";
    $scope.orderType4="hide";


    var currYear = (new Date()).getFullYear();
    var opt={};
    opt.date = {preset : 'date'};
    opt.datetime = {preset : 'datetime'};
    opt.time = {preset : 'time'};
    opt.default = {
      theme: 'android-ics light', //皮肤样式
      display: 'modal', //显示方式
      mode: 'scroller', //日期选择模式
      dateFormat: 'yyyy-mm-dd',
      lang: 'zh',
      showNow: true,
      nowText: "今天",
      startYear: currYear - 10, //开始年份
      endYear: currYear + 10 //结束年份
    };

    var optDateTime = $.extend(opt['datetime'], opt['default']);
    var optTime = $.extend(opt['time'], opt['default']);
    $("#appDateTime").mobiscroll(optDateTime).datetime(optDateTime);
    $("#appDate").val('').scroller('destroy').scroller($.extend(opt['date'], opt['default']));
    //alert($stateParams.roleId);
    if($stateParams.roleId==1||$stateParams.roleId==2){
      $scope.orderType1="";//月嫂或保姆
      $scope.orderInfo.orderType=1;
    }else if($stateParams.roleId==3){
      $scope.orderType2="";//临时钟点工
    }else if($stateParams.roleId==4){
      $scope.orderType3="";//长期钟点工
      $scope.hideTime="hide";
    }else{
      $scope.orderType4="";//其他
      $scope.hideTime="hide";
    }
    $scope.roleName=ENV.roleName;
    $scope.price=ENV.price;
    $scope.role=ENV.role;


    var times=[];
    $(".jw-table .col").click(function(){
      if($(this).hasClass("check")){
        $(this).removeClass("check");
        var val=$(this).html();
        $.each(times,function(index,item){
          // index是索引值（即下标）   item是每次遍历得到的值；
          if(item===val){
            times.splice(index,1);
          }
        });
      }else{
        $(this).addClass("check");
        times.push($(this).html());
      }

    });

    $scope.submitAddOrderForm= function () {
      console.log($scope.orderInfo);
      //alert($("#appDate").val());
      //var timestamp2 = new Date($("#appDate").val());
      //str = $("#appDate").val().replace(/-/g,"/");
      //var date = new Date(str );
      if(ENV.userId==""){
        layer.msg("请先登入");
      }else{
        if($stateParams.roleId==3){
          if($scope.orderInfo.timeSelect==2){
            $scope.orderInfo.timeSelect="13:30";
          }else{
            $scope.orderInfo.timeSelect="08:00";
          }
        }

        if($stateParams.roleId==1||$stateParams.roleId==2||$stateParams.roleId==3||$stateParams.roleId==4){
          $scope.orderInfo.serverdate=$("#appDate").val();
        }else{
          $scope.orderInfo.servertime2=$("#appDateTime").val();
          $scope.orderInfo.serverdate=$scope.orderInfo.servertime2.substr(0,10);
          $scope.orderInfo.servertime=$scope.orderInfo.servertime2.substr(11,16);
        }

        if($stateParams.roleId==4){
          console.log(times.toString());
          $scope.orderInfo.times=times.toString();
        }



        UserFactory.addOrderServer($scope.orderInfo);
      }

    }

    $(".selectxq").multiselect({
      selectedList: 4
    });

  })
  .controller('EmployeeInfoCtrl', function($scope) {

  })
  .controller('EmployerCommentCtrl', function($scope,UserFactory) {
        UserFactory.getEmployerComment();
        $scope.$on('getEmployerComment', function () {
          $scope.employerComment=UserFactory.returnEmployerComment();
        });
  })
  .controller('ForgetCtrl', function($scope,$stateParams,UserFactory) {
      $scope.userData={};
      $scope.submitForgetPasswordForm= function () {
        console.log($scope.userData);
        if($stateParams.type==1){
          console.log("ddd");
          UserFactory.forgetEmployer($scope.userData.phone);
        }else{
          console.log("111");
          UserFactory.forgetEmployee($scope.userData.phone);
        }
      }
  })
  .controller('EditPasswordCtrl', function($scope,ENV,UserFactory) {
    //声明对象
    $scope.userData={
      password:'',
      password2:'',
      id:ENV.userId
    };
    $scope.submitEditPasswordForm= function (type) {
      if(type=="employer"){  //雇主
        console.log($scope.userData.password);
        UserFactory.editPassword($scope.userData);
      }else{  //雇员
        console.log("雇员");

      }
    }
  })
;
